﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using System.IO;

namespace KnowledgeCommunity.Web.DbHelper
{
    public class CommodityImageHelper
    {
        CKCDB mydb = new CKCDB();
        /// <summary>
        /// FindAll()
        /// </summary>
        /// <returns></returns>
        public IEnumerable<CommodityImage> FindAll()
        {
            var apps = from n in mydb.CommodityImages
                       orderby n.AddTime descending
                       select n;
            return apps;
        }
        /// <summary>
        /// FindByShapeCode()
        /// </summary>
        /// <param name="code">图片所属商品的编码</param>
        /// <returns></returns>
        public IEnumerable<CommodityImage> FindByShapeCode(string code)
        {
            var apps = from n in mydb.CommodityImages
                       where n.ShapeCode == code
                       orderby n.AddTime descending
                       select n;
            return apps;
        }
        /// <summary>
        /// FindById(int id)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public CommodityImage FindById(int id)
        {
            var app = mydb.CommodityImages.Find(id);
            return app;
        }

        /// <summary>
        /// return 0-Fail; 1-Success
        /// </summary>
        /// <param name="model">CommodityImage</param>
        /// <returns></returns>
        public int Create(CommodityImage model)
        {
            int type = 0;
            try
            {
                mydb.CommodityImages.Add(model);
                mydb.SaveChanges();
                return type = 1;
            }
            catch (Exception ex)
            {
                string message = "Create in table<CommodityImages>" + ex.ToString();
                WriteLog.WriteSysLog(message);
                return type;
            }
        }

        /// <summary>
        /// return 0-Fail; 1-Success
        /// </summary>
        /// <param name="model">CommodityImage</param>
        /// <returns></returns>
        public int Delete(int id)
        {
            var model = FindById(id);
            string path = model.ImgUrl;
            int type = 0;
            try
            {
                mydb.CommodityImages.Remove(model);
                mydb.SaveChanges();
                //删除图片文件
                File.Delete(path);
                return type = 1;
            }
            catch (Exception ex)
            {
                string message = "Delete in table<CommodityImages>" + ex.ToString();
                WriteLog.WriteSysLog(message);
                return type;
            }
        }
    }
}